//创建用户相关的小仓库
import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user';
import  type {loginFormData,loginResponseData,userInfoResponseData} from '@/api/user/type';
import type { UserState } from './types/types'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '../../utils/token'
import { constantRoute,asyncRoute,anyRoute } from '../../router/routes'
import router from '../../router/index';
//@ts-ignore
//引入深拷贝方法
import cloneDeep from 'lodash/cloneDeep'
//用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asyncRoute:any,routes:any){
   return  asyncRoute.filter((item:any)=>{
       if(routes.includes(item.name)){
         if(item.children&&item.children.length>0){
         item.children = filterAsyncRoute(item.children,routes)
         }
         return true
       }
     })
}

//计算当前用户需要展示的异步路由

let useUserStore = defineStore('User', {
  state: (): any=> {
    return {
      token: GET_TOKEN(), //用户唯一标识token
      menuRoutes: constantRoute, //仓库存储生成菜单需要数组（路由）
      username: '',
      avatar: '',
      buttons:[],
      asyncArr:[]//存储需要加载的异步路由（到时候方便退出登录时动态的移除）
    }
  },
  actions: {
    //用户登录的方法
    async userLogin(data: loginFormData) {
      let result: loginResponseData= await reqLogin(data)
      if (result.code == 200) {
        this.token = result.data as string
        SET_TOKEN(result.data as string)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    //获取用户信息的方法
    async userInfo() {
      let result:userInfoResponseData = await reqUserInfo()
      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar;
        this.buttons=result.data.buttons;
        //处理完毕需要加载的异步路由
        let userAsyncRoute = filterAsyncRoute(cloneDeep(asyncRoute),result.data.routes);
        //存储需要加载的异步路由
        this.asyncArr=userAsyncRoute;
        //菜单需要的数据整理完毕
        this.menuRoutes=[...constantRoute,...userAsyncRoute,anyRoute];
        //目前路由器管理的只有常量路由：用户计算完毕异步路由，任意路由动态追加
        [...userAsyncRoute,anyRoute].forEach((route:any)=>{
            router.addRoute(route) 
        })
        //打印当前用户全部的路由
       // console.log(router.getRoutes())
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    //退出登录方法
    async userLogout() {
      let result:any = await reqLogout()
      if (result.code == 200) {
        (this.token = ''),
          (this.username = ''),
          (this.avatar = ''),
          //退出登陆时，动态的移除异步路由组件
          [...this.asyncArr,anyRoute].forEach((route:any)=>{
            router.removeRoute(route.name) 
        })   
          REMOVE_TOKEN();
          return 'ok'
      }else{
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {
  },
})
export default useUserStore
